import { NextResponse } from 'next/server';
import { CACHE_INFORMATION, BAIDU_AK, AMAP_KEY } from '@/config/settings';
const cache = new Map();

const getClientIP = (req) => {
  return (req.headers.get('x-real-ip') || req.headers.get('x-forwarded-for')?.split(',')[0] || req.ip || '');
};

const getFromBaiduMap = async (ip) => {
  const res = await fetch(`https://api.map.baidu.com/location/ip?ip=${ip}&ak=${BAIDU_AK}&coor=bd09ll`);
  const data = await res.json();
  if (data.status !== 0) { return null; }
  const result = { province: data.content.address_detail?.province, city: data.content.address_detail?.city, district: data.content.address_detail?.district, address: data.content.address, location: data.content.point };
  return result;
};

const getFromAMap = async (ip) => {
  const res = await fetch(`https://restapi.amap.com/v3/ip?ip=${ip}&key=${AMAP_KEY}`);
  const data = await res.json();
  if (data.status !== '1') { return null; }
  const result = { province: data.province, city: data.city, adcode: data.adcode, rectangle: data.rectangle };
  return result;
};

const getFromIpApi = async (ip) => {
  const res = await fetch(`http://ip-api.com/json/${ip}?lang=zh-CN`);
  const data = await res.json();
  if (data.status !== 'success') { return null; }
  return { country: data.country, province: data.regionName, city: data.city, isp: data.isp, lat: data.lat, lon: data.lon, };
};


export async function GET(req) {
  const ip = getClientIP(req);
  if (!ip) { return NextResponse.json({ error: '无法获取 IP 地址' }, { status: 400 }); }

  const cached = cache.get(ip);
  const now = Date.now();
  if (cached && cached.expires > now) { return NextResponse.json({ ip, ...cached.data }); }

  try {
    const result = {};
    const baidumap = await getFromBaiduMap(ip);
    if (baidumap) { result.baidumap = baidumap; }
    const amap = await getFromAMap(ip);
    if (amap) { result.amap = amap; }
    const ipapi = await getFromIpApi(ip);
    if (ipapi) { result.ipapi = ipapi; }
    cache.set(ip, { expires: now + CACHE_INFORMATION, data: result });
    return NextResponse.json({ ip, ...result });
  } catch (err) {
    return NextResponse.json({ ip, error: '请求信息失败'}, { status: 500 });
  }
}
